package cn.zs.supply.common.utils;


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.IOUtils;
@Slf4j
public class HttpPostUtil {

    /**
     * 文件下载
     * @param imageNetwork 图片地址
     * @param targetPath 下载目录
     * @param fileName 文件名
     * @return true:成功  false:失败
     */
    public static boolean loaddown(String imageNetwork, String targetPath, String fileName) {
        boolean bool = true;
        InputStream is = null;
        BufferedOutputStream buff = null;
        try {
            is = new URL(imageNetwork).openStream();
            if (is != null && is.available() > 0) {
                File file = new File(targetPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                //String imgPath = targetPath + File.separator + (System.currentTimeMillis()+"_")+fileName;
                String imgPath = targetPath + File.separator + fileName;
                //测试需要,暂时跳过保存文件
//                if(Files.exists(Paths.get(imgPath))){
//                    log.error("将要保存到本地的文件,跳过...");
//                    return false;
//                }
                buff = new BufferedOutputStream(new FileOutputStream(imgPath));
                IOUtils.copy(is, buff);
            } else {
                bool = false;
            }
        } catch (Exception e) {
			//("下载文件异常：imageNetwork：" + imageNetwork + "-->fileName：" + fileName);
            log.error("文件下载出错, imageNetwork:[{}], targetPath:[{}], fileName:[{}]",
                    imageNetwork, targetPath, fileName);
            log.error("",e);
            bool = false;

        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(buff);
        }
        return bool;
    }
    
    /**
     * 读取客户端发送的JSON数据
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestWrapperData(HttpServletRequest request) throws IOException{
        String result="";
        try {
            InputStream in = request.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine())!=null){
                sb.append(line);
            }
            //解码
            result = sb.toString();
//            result=URLDecoder.decode(reqBody, HTTP.UTF_8);
        } catch (Exception e) {
            result="";
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 读取客户端发送的JSON数据，无解码
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestJson(HttpServletRequest request) throws IOException{
        String result="";
        String privatekey="";
        try {
            privatekey = request.getAttribute("privatekey")+"";
            InputStream in = request.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine())!=null){
                sb.append(line);
            }
            //解码
            result = sb.toString();
//            result=URLDecoder.decode(reqBody, HTTP.UTF_8);
        } catch (Exception e) {
            result="";
            e.printStackTrace();
        }
        if(StringUtil.isNotEmpty(result)){
            JSONObject requestJSON = JSONObject.parseObject(result);
            //判断是否存在数据加密key,存在则数据解密，反之直接返回
            if(StringUtil.isNotEmpty(privatekey)){
                //获取密文
                String dataStr = requestJSON.getString("data");
                //解密
                result = RSAUtil.decrypt(dataStr,privatekey);
            }
        }
        return result;
    }
       
}
